package ThreadDemo;

/**
 * 阻塞队列
 */
class BlockinQueue{
    int[] nums=new int[1000];
    private int head=0;
    private int tail=0;
    private volatile int size=0;
    public int take() throws InterruptedException {
        int ret = -1;
        synchronized (this) {
            if(size==0){
                wait();
            }
            ret = nums[head];
            head++;
            if (head == nums.length) {
                head = 0;
            }
            size--;
            notify();
        }
        return ret;
    }
    public void put(int k) throws InterruptedException {
        synchronized (this) {
            if(size==nums.length){
                wait();
            }
            nums[tail] = k;
            tail++;
            if (tail == nums.length) {
                tail = 0;
            }
            size++;
            notify();
        }
    }


}
public class ThreadDemo11 {
    public static void main(String[] args) {
        BlockinQueue blockinQueue=new BlockinQueue();
        Thread thread1=new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    try {
                        blockinQueue.put(i);
                        System.out.println("生产"+i);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        thread1.start();
        Thread thread2=new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    try {
                        int ret = blockinQueue.take();
                        System.out.println("消费"+ret);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        thread2.start();
    }
}
